#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Time    : 2025/5/8 16:52
@Author  : HZP
@File    : account_service.py
"""
from dataclasses import dataclass
from datetime import timedelta, datetime
from typing import Any
from uuid import UUID

from flask import request
from injector import inject

from internal.exception import FailException
from internal.model import Account
from internal.service.base_service import BaseService
from pkg.sqlalchemy import SQLAlchemy
from pkg.password.password import compare_password
from internal.service.jwt_service import JwtService

@inject
@dataclass
class AccountService(BaseService):
    db: SQLAlchemy
    jwt_service: JwtService

    def get_account(self, account_id: UUID) -> Account:
        return self.get(Account, id=account_id)

    def password_login(self, email: str, password: str) -> dict[str,Any]:
        """处理登录相关业务逻辑"""
        #1、根据邮箱地址获取账号信息
        account =self.get_account_by_email(email)
        if not account:
            raise FailException("账号不存在或者密码错误，请核实后重试")
        #2、校验密码正确与否
        if not account.is_password_set or not compare_password(
            password=password,
            password_hashed_base64=account.password,
            salt_base64=account.password_salt
        ):
            raise FailException("账号不存在或者密码错误，请核实后重试")
        #3、生成凭证信息
        expire_at=int((datetime.now() + timedelta(days=30)).timestamp())
        payload={
            "sub":str(account.id),
            "exp":expire_at,
            "iss":"llmops"
        }
        access_token = self.jwt_service.generate_token(payload)
        # 4.更新账号的登录信息
        self.update(
            account,
            last_login_at=datetime.now(),
            last_login_ip=request.remote_addr,
        )

        return {
            "expire_at": expire_at,
            "access_token": access_token,
        }


    def get_account_by_email(self, email: str) -> Account:
        return self.db.session.query(Account).filter(Account.email == email).one_or_none()